package com.findFish.controlPlatform;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import com.fazecast.jSerialComm.SerialPort;

@Component
@ServerEndpoint("/ws/{cageId}") // 传入的网箱id
@Slf4j
public class websocketServer {
//    存储会话对象
    private static Map<String , Session> sessionMap = new HashMap<>();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        System.out.println("客户端：" + sid + "建立连接");
        sessionMap.put(sid, session);
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, @PathParam("sid") String sid) {
        System.out.println("收到来自客户端：" + sid + "的信息:" + message);
    }

    /**
     * 连接关闭调用的方法
     *
     * @param sid
     */
    @OnClose
    public void onClose(@PathParam("sid") String sid) {
        System.out.println("连接断开:" + sid);
        sessionMap.remove(sid);
    }

    /**
     * 群发
     *
     * @param message
     */
    public void sendToAllClient(String message) {
        Collection<Session> sessions = sessionMap.values();
        for (Session session : sessions) {
            try {
                SerialPort serialPort = SerialPort.getCommPort("COM4");
                serialPort.setComPortParameters(9600, 8, SerialPort.ONE_STOP_BIT, SerialPort.NO_PARITY);

                if (serialPort.openPort()) {
                    log.info("串口已打开！");
                    // 创建缓冲区
                    byte[] buffer = new byte[1024];
                    while (true) {
                        int numRead = serialPort.readBytes(buffer, buffer.length);
                        if (numRead > 0) {
                            log.info("接收到数据：" + new String(buffer, 0, numRead, Charset.forName("GBK")));
                            session.getBasicRemote().sendText(message);
                        }
                    }
                } else {
                    log.error("无法打开串口！");
                }
                //服务器向客户端发送消息
//                session.getBasicRemote().sendText(message);

            } catch (Exception e) {

            }
        }
    }

}
